package switchviz.core.mib;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;

import org.apache.log4j.Logger;

import switchviz.Application;
import switchviz.core.ResourceManager;
import switchviz.gui.component.IListener;
import switchviz.gui.component.PopupMenu;
import switchviz.gui.component.TestNetworkOptionPane;
import switchviz.gui.component.XMLTreeNode;
import switchviz.network.snmp.SnmpWalkerFrame;


public class MIBPanel extends JPanel implements IListener
{
	private static final long serialVersionUID = 5007676439230480512L;

	private static Logger logger = Logger.getLogger(MIBPanel.class);
	
	private MIBTree _xmltree = null;
	private MIBConfigurationPanel _configpanel = null;
	private PopupMenu _popup;
	private MIBDataModel _actdatamodel = new MIBDataModel();
	private MIBDataModel _datamodel = null;
	
	public MIBPanel()
	{
		if (logger.isInfoEnabled()) { logger.info("Initialize ..."); }
		initialize();
	}
	
	private void initialize()
	{
		this.setLayout(ResourceManager.getInstance().getBorderLayout());
		this.add(getConfigurationPanel(), BorderLayout.CENTER);
		this.add(getMIBTree(), BorderLayout.WEST);
	}
	
	private MIBConfigurationPanel getConfigurationPanel()
	{
		if (_configpanel == null)
		{
			_configpanel = new MIBConfigurationPanel();
			_configpanel.addListener(this);
		}
		return _configpanel;
	}
	
	private MIBTree getMIBTree()
	{
		if (_xmltree == null)
		{
			try 
			{
				_xmltree = new MIBTree(ResourceManager.getInstance().getMIBConfigurationFile());
				_xmltree.getTree().addTreeSelectionListener(this);
				_xmltree.getTree().addMouseListener(this);
				_popup = new PopupMenu(new String[] { ResourceManager.getInstance().getActionAddItem(), 
					ResourceManager.getInstance().getActionRemoveItem(), 
					ResourceManager.getInstance().getActionRefresh() }, this);
				_xmltree.getTree().setSelectionRow(0);
			} 
			catch (Exception e) { logger.error(e.getMessage()); }
		}
		return _xmltree;
	}
	
	private MIBDataModel getDataModel()
	{
		if (_datamodel == null)
		{
			_datamodel = new MIBDataModel();
		}
		return _datamodel;
	}
	
	public void actionPerformed(ActionEvent e) 
	{
		String command = e.getActionCommand();
		try 
    	{
	        if (ResourceManager.getInstance().getActionAddItem().equals(command)) 
	        {
	        	getMIBTree().addMIBNode("name :: 0", "name", "0");
	        	getMIBTree().saveXML();
	        } 
	        else if (ResourceManager.getInstance().getActionRemoveItem().equals(command)) 
	        {
	        	getMIBTree().removeNode();
	        	getMIBTree().saveXML();
	        }
	        else if(ResourceManager.getInstance().getActionRefresh().equals(command))
	        {
	        	getMIBTree().reload();
	        	getMIBTree().getTree().setSelectionRow(0);
	        }
	        else if (ResourceManager.getInstance().getActionChange().equals(command))
	        {
	        	if (((XMLTreeNode)getMIBTree().getTree().getLastSelectedPathComponent()).isRoot()) { return; }
	    		_datamodel = getConfigurationPanel().getValues();
	        	if (_datamodel.getName().trim().equals("") || _datamodel.getOID().trim().equals(""))
	    		{
	    			JOptionPane.showMessageDialog(this,
	    				    "Please insert a name and an id.",
	    				    "Form not complete!",
	    				    JOptionPane.WARNING_MESSAGE);
	    			return;
	    		}
	        	getMIBTree().changeCurrentNode(_datamodel);
	        	getMIBTree().saveXML();
	        }
	        else if (ResourceManager.getInstance().getActionTest().equals(command))
	        {
	        	new TestNetworkOptionPane(Application.getInstance().getMainFrame(), _actdatamodel);
	        }
	        else if(ResourceManager.getInstance().getActionStart().equals(command))
	        {
	        	new SnmpWalkerFrame(_actdatamodel.getOID());
	        }
    	}
		catch (Exception e1) 
		{ 
			logger.error(e1.getMessage()); 
		}
	}
	
	public void valueChanged(TreeSelectionEvent evt) 
	{
		int j;
		String name = "", oid = "";
		
		XMLTreeNode currentnode = (XMLTreeNode)evt.getPath().getLastPathComponent();
		getDataModel().setName(currentnode.getElement().getAttributeValue(MIBTree.MIBNODENAME));
		getDataModel().setOID(currentnode.getElement().getAttributeValue(MIBTree.MIBNODEOID));
		getDataModel().setDescription(currentnode.getElement().getChildTextNormalize(MIBTree.MIBNODEDESCRIPTION));
		getDataModel().setType(currentnode.getElement().getChildTextNormalize(MIBTree.MIBNODETYPE));
		
		if(currentnode.getElement().getChild(MIBTree.MIBNODERANGE) != null && 
				currentnode.getElement().getChild(MIBTree.MIBNODERANGE).getAttributes().size() == 2 &&
			currentnode.getElement().getChild(MIBTree.MIBNODERANGE).getAttributeValue(MIBTree.MIBNODERANGEFROM).length() != 0 &&
			currentnode.getElement().getChild(MIBTree.MIBNODERANGE).getAttributeValue(MIBTree.MIBNODERANGETO).length() != 0)
		{
			getDataModel().setRangeLow(Long.valueOf(currentnode.getElement().getChild(MIBTree.MIBNODERANGE).getAttributeValue(MIBTree.MIBNODERANGEFROM)));
			getDataModel().setRangeHigh(Long.valueOf(currentnode.getElement().getChild(MIBTree.MIBNODERANGE).getAttributeValue(MIBTree.MIBNODERANGETO)));
		}
		else
		{
			getDataModel().setRangeLow(0);
			getDataModel().setRangeHigh(0);
		}
		
		if(currentnode.getElement().getChild(MIBTree.MIBNODEPORT) != null)
			getDataModel().setPortRequired(Boolean.valueOf(currentnode.getElement().getChildTextNormalize(MIBTree.MIBNODEPORT)));
		else
			getDataModel().setPortRequired(false);
		
		getConfigurationPanel().setValues(getDataModel());
    	Object[] pathlist = evt.getPath().getPath();
    	name = "";
    	oid = "";
    	for(j = 1; j < pathlist.length; ++j)
    	{
    		currentnode = (XMLTreeNode) pathlist[j];
    		name += currentnode.getElement().getAttributeValue(MIBTree.MIBNODENAME) + ".";
    		oid += currentnode.getElement().getAttributeValue(MIBTree.MIBNODEOID) + ".";
    	}
    	if(j > 1)
    	{
        	name = name.substring(0, name.length() - 1);
        	oid = oid.substring(0, oid.length() - 1);
        	
        	_actdatamodel.setOID(oid);
        	_actdatamodel.setName(name);
        	_actdatamodel.setPortRequired(Boolean.valueOf(currentnode.getElement().getChildText(MIBTree.MIBNODEPORT)));
        	
        	Application.getInstance().getMainFrame().getMainPanel().getStatusBar().setText("  " + name + "  [" + oid + "]");
        	
    	}
    	else
    	{
    		Application.getInstance().getMainFrame().getMainPanel().getStatusBar().setText("SwitchViz");
    	}
    	if(currentnode.getElement().getChildren(MIBTree.MIBNODE).size() == 0)
    	{
    		getConfigurationPanel().setTestEnable(true);
    	}
    	else
    	{
    		getConfigurationPanel().setTestEnable(false);
    	}
	}
	
	public void mousePressed(MouseEvent e) 
	{
		if (e.isPopupTrigger() || e.getButton() == 3) 
			_popup.show(e.getComponent(), e.getX(), e.getY());
	}
	
	public void mouseClicked(MouseEvent arg0) {}
	public void mouseEntered(MouseEvent arg0) {}
	public void mouseExited(MouseEvent arg0) {}
	public void mouseReleased(MouseEvent arg0) {}
}
